import time, math
from builtins import str # this is for backwards compatibility with python2

########## This function prints the amount of time elapsed and remaining, given a for loop.
def printRemainingTime(tic, NumItersDone, NumItersTotal):
    toc = time.time()
    elapsedTime = toc-tic
    remainingTime = elapsedTime/NumItersDone * (NumItersTotal-NumItersDone)
    print("Iteration " + str(NumItersDone) + " out of " + str(NumItersTotal) + \
        " - Elapsed time: " + "{:.1f}".format(elapsedTime) + \
        " sec - Remaining time: " + "{:.1f}".format(remainingTime) + " sec.");

import csv

##########
#### This function appends data onto an existing CSV file (one row per data item).
### Inputs:
# data: 		list of lists
#					outside list is a list of data item
#					for each item, a list of fields
# fileName:		string
# delim:		delimiter for CSV file --> string (e.g. ',')
### No output
##########

def appendData2File(data, fileName, delim):
    with open(fileName, 'a') as fp:
        a = csv.writer(fp, delimiter=delim, lineterminator='\n')
        a.writerows(data)


##########
#### This function reads data from a CSV file.
### Inputs:
# fileName:		string
# delim:		delimiter for CSV file --> string (e.g. ',')
# skipFirstRow:	boolean => if True, then data is read starting on the 2nd row
#								(useful if the first row contains the headers)
# fieldIds:		list of integers => id's of the columns for which we want the data
#						(column index starts at 1)
### Outputs:
# data: 		list of lists
#					outside list is a list of fields
#						for each field, a list of NumRows items, where NumRows
#						is the number of records.
##########
def readDataFromFile(fileName, delim, skipFirstRow, fieldIds):
    NumFields = len(fieldIds)
    data = [[] for _ in range(NumFields)]
    with open(fileName, 'rt') as csvfile:
        myreader = csv.reader(csvfile, delimiter=delim)
        if skipFirstRow:
            next(myreader)
        for row in myreader:
            for ii in range(0,NumFields):
                value = row[fieldIds[ii]-1]
                data[ii].append(value)
    return data
